package com.xian.im.modules.command.cmd;

import com.xian.feign.UserChannelClient;
import com.xian.im.common.constant.CommandConstant;
import com.xian.im.common.model.session.Attributes;
import com.xian.im.common.model.vo.UserDetail;
import com.xian.im.common.proto.MsgRequest;
import com.xian.im.common.proto.MsgResponse;
import com.xian.im.common.utils.bussiness.ChannelClientContextUtil;
import com.xian.im.common.utils.sys.SpringContextHolder;
import com.xian.im.modules.command.Command;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

/**
 * @program: xian-im-server
 * @description:
 * @author: liru.xian
 * @create: 2021-01-27 09:26
 **/
@Slf4j
public class P2PHandlerCommand implements Command {

    /**
     * 执行
     *
     * @param request
     * @param ctxId
     */
    @Override
    public void exec(MsgRequest request, String ctxId) {
        UserChannelClient userChannelClient = SpringContextHolder.getBean(UserChannelClient.class);
        ChannelHandlerContext ctx = ChannelClientContextUtil.getCtxById(ctxId);
        if (ctx != null) {
            //点对点
            String toAccount = request.getToAccount();
            MsgResponse response= MsgResponse.buildSuccess();
            BeanUtils.copyProperties(request,response);
            UserDetail user = ctx.channel().attr(Attributes.SESSION).get().build();
            response.setUser(user);
            response.setBody(request.getBody());
            userChannelClient.pushPlatformMessage(toAccount,response);
        }
    }

    /**
     * 获取命令
     *
     * @return
     */
    @Override
    public Integer getCmd() {
        return CommandConstant.P2P_CMD;
    }
}
